package com.beta.nfc_beta;

import java.util.ArrayList;

import com.beta.DB.DBHelper;
import com.beta.nfc_beta.vars.Vars;
import com.beta.password_menu.ConfirmPasswordActivity;
import com.beta.password_menu.SetPasswordActivity;
import com.test.db.TestDBhHelper;

import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Event;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher.ViewFactory;
import android.content.SharedPreferences;
import android.database.Cursor;

@SuppressLint("WorldWriteableFiles")
public class MenuActivity extends Activity {
	//pattern password part:
	private SharedPreferences AppIni;

	
	//about images in screen
	ImageSwitcher iSwitcher;

	TextView tv_bank;
	TextView tv_card;
	int index=0;
	int[] images;
	DBHelper dbHelper;
	static String[] pop_menu={"PbocCard","MifareCard"};
	
	static final String tag="Menu2Activity";
	//TestDBhHelper dbTestHelper;
	@SuppressLint("WorldReadableFiles")
	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.menu2);
		iSwitcher=(ImageSwitcher)this.findViewById(R.id.imageSwitcher);
		tv_bank=(TextView)findViewById(R.id.menu_bank_name);
		tv_card=(TextView)findViewById(R.id.menu_card_number);
		dbHelper=new DBHelper(this);
		iSwitcher.setFactory(new ViewFactory() {  
			  
            public View makeView() {  
                return new ImageView(MenuActivity.this);  
            }  
        }); 
		iSwitcher.setOnTouchListener(new View.OnTouchListener() {
			float downX,upX;
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				float X=event.getX();
				if(event.getAction()==MotionEvent.ACTION_DOWN){
					downX=event.getX();
				}else if(event.getAction()==MotionEvent.ACTION_UP){
					upX=event.getX();
					int iDownX=(int)downX;
					int iUpX=(int)upX;
					if(iDownX-iUpX>100){//<----
						//animation
						//Toast.makeText(getApplicationContext(), "Right", Toast.LENGTH_SHORT).show();
						index++;
						index%=images.length;
						//updateTextView(index);
						/*iSwitcher.setInAnimation(AnimationUtils.loadAnimation(Menu2Activity.this,
				                R.anim.anim_to_left));	*/					
				        /*iSwitcher.setOutAnimation(AnimationUtils.loadAnimation(Menu2Activity.this,
				        		R.anim.anim_to_left));*/
						iSwitcher.setInAnimation(AnimationUtils.loadAnimation(MenuActivity.this,
				                R.anim.slide_in_right));
						iSwitcher.setOutAnimation(AnimationUtils.loadAnimation(MenuActivity.this,
				        		R.anim.slide_out_left));
						iSwitcher.setImageResource(images[index]);
					}else if(iUpX-iDownX>100){//---->
						//animation
						//Toast.makeText(getApplicationContext(), "Left", Toast.LENGTH_SHORT).show();
						if(--index<0){
							index+=images.length;
							index%=images.length;
							//updateTextView(index);
						}
						/*iSwitcher.setInAnimation(AnimationUtils.loadAnimation(Menu2Activity.this,
				                R.anim.anim_to_right));
				        iSwitcher.setOutAnimation(AnimationUtils.loadAnimation(Menu2Activity.this,
				        		R.anim.anim_to_right));*/
				        iSwitcher.setInAnimation(AnimationUtils.loadAnimation(MenuActivity.this,
				                R.anim.slide_in_left));
				        iSwitcher.setOutAnimation(AnimationUtils.loadAnimation(MenuActivity.this,
				                R.anim.slide_out_right));
						iSwitcher.setImageResource(images[index]);
					}else if(Math.abs(iUpX-iDownX)<10){
						iClick(iSwitcher);
					}else{
						return false;
					}
					//update textview
					
				}
				return true;
			}
		});
		iSwitcher.setClickable(true);
		
		//start pattern password
		AppIni = getSharedPreferences("configure", Context.MODE_WORLD_WRITEABLE
				| Context.MODE_WORLD_READABLE);
		boolean FirstTimeOpenApp = AppIni.getBoolean("FirstTimeOpenApp", true);
		if (FirstTimeOpenApp) {
			Intent i = new Intent(this,SetPasswordActivity.class);
			//i.setClass(this, SetPasswordActivity.class);
			startActivityForResult(i, Vars.RESULTFROMSETPASSWORD);
		} else {
			Intent i = new Intent();
			Bundle band = new Bundle();
			band.putString("PackageName", "");
			band.putString("ClassName", "");
			i.putExtras(band);
			i.setClass(this, ConfirmPasswordActivity.class);
			startActivityForResult(i, Vars.RESULTFROMCONFIRMPASSWORD);
		}
	

		updateImages();	
	
		//dbTestHelper=new TestDBhHelper(this);
		//dbTestHelper.addTwoItems();
	}
	
	public void updateTextView(int index){
		if(index!=0){
			tv_bank.setText("");
			tv_card.setText("");
			Cursor card=dbHelper.query(String.valueOf(index+1));
			if (card != null){		
				Log.d(tag, String.valueOf(card.getPosition()));
				if(card.moveToFirst()){									
					do{					
						if(String.valueOf(card.getString(card.getColumnIndex("ID"))) != null){
							tv_card.setText(String.valueOf(card.getString(card.getColumnIndex("ID"))));
							break;
						}
					}while(card.moveToNext());
				}
			}
		}else{
			tv_bank.setText("Add Card");
			tv_card.setText("");
		}
	}

	public void iClick(View view){
		if(index<images.length-1){
			Intent turn_info_intent = new Intent(MenuActivity.this,CardInfoActivity.class);
			String ID = String.valueOf(index+1);//database start with 0
			turn_info_intent.putExtra("picture_res_id", images[index]);
			turn_info_intent.putExtra("ID",ID);
			turn_info_intent.putExtra("source", "Menu");
			this.startActivity(turn_info_intent);
			overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
			//error = this.getIntent();
			//errors = error.getExtras().getString("back_info");
			//Toast.makeText(this, errors, Toast.LENGTH_SHORT).show();
		}else{//add new card
			final Intent add_card=new Intent(MenuActivity.this,ChooseCardActivity.class);
			 Builder builder=new AlertDialog.Builder(MenuActivity.this);
			    builder.setTitle("Select Card Type");
			    builder.setItems(pop_menu,
			    		new DialogInterface.OnClickListener(){

					@Override
					public void onClick(DialogInterface dialog,
							int which) {
						Log.d("Menu2Activity", "which="+which);
						if(which==0){
							add_card.putExtra("Mode",Vars.BANK_MODE);
						}else
							add_card.putExtra("Mode", Vars.CREDIT_MODE);
						startActivity(add_card);
						overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
					}
			    	
			    });		 
			    AlertDialog dialog=builder.create();
			    dialog.show();
			    overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
		}
	}

	private void updateImages(){
		int i=0;
		dbHelper=new DBHelper(this);
		if(!dbHelper.isEmpty()){
			Log.d(tag, "empty?"+dbHelper.isEmpty());
			ArrayList<Integer> picList=dbHelper.getPictures();
			images=new int[picList.size()+1];
			for(;i<picList.size();i++){
				images[i]=picList.get(i);
			}
		}else{
			images=new int[1];
		}
		images[i]=R.drawable.add;
		dbHelper.close();
		iSwitcher.setImageResource(images[index]);
	}
	
	@Override
	public void onResume(){
		super.onResume();
		updateImages();
	}
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.menu, menu);
		return true;
	}	

	private long exitTime = 0; 
	@Override 
	public boolean onKeyDown(int keyCode, KeyEvent event) {	
		if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){ 
			if((System.currentTimeMillis()-exitTime) > 2000){ 
				Toast.makeText(getApplicationContext(), "Tap again to exit", Toast.LENGTH_SHORT).show();
				exitTime = System.currentTimeMillis(); 
			} else { 
				//dbTestHelper.delete();
				finish(); 
				System.exit(0); 
			} 
			return true; 
		} 
		return super.onKeyDown(keyCode, event); 
	} 

	

}